package org.seed.quantum.message.plugins;

import org.seed.quantum.memory.BufferFactory;
import org.seed.quantum.memory.BufferPagePool;
import org.seed.quantum.message.ssl.SslAsynchronousSocketChannel;
import org.seed.quantum.message.ssl.SslAuthEnum;
import org.seed.quantum.message.ssl.SslService;
import java.io.InputStream;
import java.nio.channels.AsynchronousSocketChannel;

public class SslPlugin <T> extends AbstractPlugin<T>{

    private SslService sslService;
    private BufferPagePool bufferPagePool;
    private boolean init = false;

    public SslPlugin() {
        this.bufferPagePool = BufferFactory.IDLE_BUFFER_FACTORY.create();
    }

    public SslPlugin(BufferPagePool bufferPagePool) {
        this.bufferPagePool = bufferPagePool;
    }

    public void initForServer(InputStream keyStoreInputStream, String keyStorePassword, String keyPassword, SslAuthEnum authEnum) {
        initCheck();
        sslService = new SslService(false, authEnum);
        sslService.initKeyStore(keyStoreInputStream, keyStorePassword, keyPassword);
    }

    public void initForClient() {
        initForClient(null, null);
    }

    public void initForClient(InputStream trustInputStream, String trustPassword) {
        initCheck();
        sslService = new SslService(true, null);
        sslService.initTrust(trustInputStream, trustPassword);
    }

    private void initCheck() {
        if (init) {
            throw new RuntimeException("plugin is already init");
        }
        init = true;
    }

    @Override
    public final AsynchronousSocketChannel shouldAccept(AsynchronousSocketChannel channel) {
        return new SslAsynchronousSocketChannel(channel, sslService, bufferPagePool.allocateBufferPage());
    }
}
